package reflect

import kotlin.reflect.KMutableProperty1
import kotlin.reflect.full.memberProperties

object ReflectTest {
    fun test(){
        val student = Student("张三", 99.5, 185)
        val school = School("清华", "北京")

        readMembers(student)
        readMembers(school)

        modifyAddressMember(school)

        readMembers(school)
        readMembers(student)
    }

    private fun readMembers(obj: Any) {
        obj::class.memberProperties.forEach {
            println("${obj::class.simpleName}.${it.name} = ${it.getter.call(obj)}")
        }
    }

    private fun modifyAddressMember(obj: Any){
        obj::class.memberProperties.forEach{
            if (it.name == "address" &&
                it is KMutableProperty1 &&
                it.setter.parameters.size == 2 &&
                it.getter.returnType.classifier == String::class){
                it.setter.call(obj, "China")
                println("====Address changed.====")
            }
        }
    }
}